package com.example.desinger.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.desinger.common.R;
import com.example.desinger.entity.Classroom;
import com.example.desinger.entity.HomeWork;
import com.example.desinger.entity.StuHomeWork;
import com.example.desinger.entity.Students;
import com.example.desinger.mapper.HomeWorkMapper;
import com.example.desinger.service.ClassRoomService;
import com.example.desinger.service.HomeWorkService;
import com.example.desinger.service.StuHomeWorkService;
import com.example.desinger.service.StudentsService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.UUID;

@Service
public class HomeWorkServiceImpl extends ServiceImpl<HomeWorkMapper, HomeWork> implements HomeWorkService {
    @Value("${designer.path}")
    private String basePath;

    //花式注入
    @Autowired
    private StuHomeWorkService stuHomeWorkService;
    @Autowired
    private StudentsService studentsService;
    @Autowired
    private ClassRoomService classRoomService;





    @Override
    public R<String> saveAndProfile(HomeWork homeWork) {
        //查找班级
        LambdaQueryWrapper<Classroom> classroomLambdaQueryWrapper = new LambdaQueryWrapper<>();
        classroomLambdaQueryWrapper.eq(Classroom::getId,homeWork.getClassId());
        Classroom one2 = classRoomService.getOne(classroomLambdaQueryWrapper);
        if (one2==null){
            return R.error("这班级不存在，请您先添加班级吧");
        }

        //先添加作业
        LambdaQueryWrapper<HomeWork> lambdaQueryWrapper =
                new LambdaQueryWrapper<>();
        //查看这个班有没有这个实验
        lambdaQueryWrapper.eq(HomeWork::getClassId, homeWork.getClassId())
                .eq(HomeWork::getNickname, homeWork.getNickname());
        HomeWork one = getOne(lambdaQueryWrapper);

        if (one != null) {
            return R.error("这个班级的作业您已经发布过了");
            //已经有了这次的作业，返回
        }
        // 生成随机UUID
        String uuid = UUID.randomUUID().toString();
        String suffix = uuid + homeWork.getNickname();
        // 指定文件夹路径和名称
        Path folderPath = Paths.get(basePath, suffix);
        try {
            // 创建文件夹
            Files.createDirectories(folderPath);
            System.out.println("文件夹创建成功，路径：" + folderPath.toString());
        } catch (IOException e) {
            System.err.println("创建文件夹时出错：" + e.getMessage());
        }
        homeWork.setDirname(suffix);
        save(homeWork);
        //这个班级中没有这次的实验，添加并发送个这个班上的每一位学生
        //为个班的学生添加作业作业信息为还未上交state==0
        //搜索这个班的信息
        LambdaQueryWrapper<Students> studentsLambdaQueryWrapper =
                new LambdaQueryWrapper<>();
        studentsLambdaQueryWrapper.eq(Students::getClassId, homeWork.getClassId());

        //拿到作业的id啊
        int hw = getOne(lambdaQueryWrapper).getId();

        //拿到这个班的人数给他们插入还没交作业状态的数据
        List<Students> list = studentsService.list(studentsLambdaQueryWrapper);
        System.out.println("看看拿到的数据是不是为空？" + list);
        //为每个学生添加这次的作业
        StuHomeWork stuHomeWork = new StuHomeWork();
        for (Students students : list) {
            int classId = students.getClassId();
            int studentsId = students.getId();
            //查询这个同学是否上交了这次作业
            LambdaQueryWrapper<StuHomeWork> lambdaQueryWrapper1 =
                    new LambdaQueryWrapper<>();
            lambdaQueryWrapper1.eq(StuHomeWork::getClassId, classId)
                    .eq(StuHomeWork::getStuId, studentsId)
                    .eq(StuHomeWork::getHomeWorkId, hw);
            StuHomeWork one1 = stuHomeWorkService.getOne(lambdaQueryWrapper1);
            if (one != null) {
                System.out.println("学生：" + students.getNickname() + "的作业已经添加过了");
                continue;
            }
            stuHomeWork.setClassId(classId);
            stuHomeWork.setStuId(studentsId);
            stuHomeWork.setHomeWorkId(hw);
            stuHomeWork.setState(0);
            stuHomeWorkService.save(stuHomeWork);
        }
        return R.success("恭喜您，作业发布成功");
    }

    @Override
    public R<String> uploadFile(MultipartFile file, int stuId, int classId,
                                int homeWorkId) {
        LambdaQueryWrapper<HomeWork> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(HomeWork::getId, homeWorkId);
        HomeWork one = getOne(lambdaQueryWrapper);
        String exName = one.getDirname();
        //获取实验的文件夹的名字
        System.out.println("获取实验作业的文件夹：" + one.getDirname());
        //获取原始文件名
        String originalFilename = file.getOriginalFilename();
        //获取最后的.的索引值
        int index = originalFilename.lastIndexOf(".");
        //从索引位置向后截取.jpg
        String suffix = originalFilename.substring(index);
        //UUID作为新的文件名并且和后缀组合
        String s = UUID.randomUUID().toString() + "学生" + stuId + "教室" + classId + suffix;

        String NewPath = basePath + exName + "\\";
        System.out.println("新文件的地址" + NewPath);

        try {
            file.transferTo(new File(NewPath + s));
            System.out.println("最后转入的地址" + NewPath + s);
        } catch (IOException e) {
            e.printStackTrace();
        }
        //如果文件正常放入那就进行数据的存入
        LambdaQueryWrapper<StuHomeWork> homeWorkLambdaQueryWrapper = new LambdaQueryWrapper<>();
        homeWorkLambdaQueryWrapper.eq(StuHomeWork::getClassId, classId)
                .eq(StuHomeWork::getStuId, stuId)
                .eq(StuHomeWork::getHomeWorkId, homeWorkId);

        StuHomeWork one1 = stuHomeWorkService.getOne(homeWorkLambdaQueryWrapper);

        if (one1!=null) {
            //更新
            LambdaUpdateWrapper<StuHomeWork> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.eq(StuHomeWork::getClassId,classId)
                        .eq(StuHomeWork::getStuId,stuId)
                        .eq(StuHomeWork::getHomeWorkId,homeWorkId);
                StuHomeWork stuHomeWork = new StuHomeWork();
                stuHomeWork.setFilename(s);
                stuHomeWork.setState(1);

            boolean update = stuHomeWorkService.update(stuHomeWork, updateWrapper);

            if (update) {
                return R.success("添加成功");
            }
            return R.error("添加失败");
        }
        return R.error("请您先提交作业");
    }

    @Override
    public List<HomeWork> findById(int classId) {
        LambdaQueryWrapper<HomeWork> lambdaQueryWrapper = new LambdaQueryWrapper();
        lambdaQueryWrapper.eq(HomeWork::getClassId,classId);
        List<HomeWork> list = list(lambdaQueryWrapper);
        return list;
    }

    @Override
    public R<String> delectHomeWordById(int id) {
        //删除实验的作业和学生的作业
        LambdaQueryWrapper<HomeWork> lambdaQueryWrapper = new LambdaQueryWrapper();
        lambdaQueryWrapper.eq(HomeWork::getId,id);
        boolean remove = remove(lambdaQueryWrapper);
        if (remove){
            LambdaQueryWrapper<StuHomeWork> stuHomeWorkLambdaQueryWrapper
                    = new LambdaQueryWrapper<>();
            stuHomeWorkLambdaQueryWrapper.eq(StuHomeWork::getHomeWorkId,id);
            boolean b = stuHomeWorkService.remove(stuHomeWorkLambdaQueryWrapper);
            if (b){
                return R.success("删除成功！");
            }else {
                return R.error("删除失败！");
            }
        }else {
            return R.error("没有这个班的作业");
        }
    }

}
